<!DOCTYPE html>
<html lang="zh-CN">
	<head>
		<meta charset="UTF-8">
		<meta http-equiv="X-UA-Compatible" content="IE=edge">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<title>Document</title>
		<script src="../jQuery/jquery-3.7.1.js"></script>
		<style>
			* {
				margin: 0;
				padding: 0;
				list-style: none;
			}

			.news {
				display: flex;
				height: 120px;
				width: 600px;
				margin: 0 auto;
				padding: 20px 0;
				cursor: pointer;
			}

			.news .left {
				flex: 1;
				display: flex;
				flex-direction: column;
				justify-content: space-between;
				padding-right: 10px;
			}

			.news .left .title {
				font-size: 20px;
			}

			.news .left .info {
				color: #999999;
			}

			.news .left .info span {
				margin-right: 20px;
			}

			.news .right {
				width: 160px;
				height: 120px;
			}

			.news .right img {
				width: 100%;
				height: 100%;
				object-fit: cover;
			}
		</style>
	</head>
	<body>
		<!-- 测试的div中添加一个a标签 -->
		<!-- <div></div> -->

		<div id="app">
			<ul>
				<li class="news">
					<div class="left">
						<div class="title">5G商用在即，三大运营商营收持续下降</div>
						<div class="info">
							<span>新京报经济新闻</span>
							<span>2222-10-28 11:50:28</span>
						</div>
					</div>
					<div class="right">
						<img src="http://ajax-api.itheima.net/public/images/0.webp" alt="">
					</div>
				</li>
			</ul>
		</div>
	</body>
	<script>
		// 测试
		// $('div:first').html("<a href='http://www.baidu.com'>百度首页</a>")

		// 网页加载完成去发请求
		$.ajax({
			url: 'http://hmajax.itheima.net/api/news',
			type: 'get',
			success: function(result) {
				console.log(result.data) // 新闻数组
				let arr = result.data
				renderNews(arr)
			}
		})

		/* 通过数组数据渲染新闻列表 */
		function renderNews(arr) {
			if (arr === null || arr === undefined ||
				arr.length === 0) {
				// 结束方法
				return
			}
			// 循环
			let ul_html = ''
			for (let i = 0; i < arr.length; i++) {
				// 每次循环的对象产生一个与样例结构一致的li，并且添加到ul中
				let obj = arr[i]
				ul_html += "<li class='news'>"
				ul_html += "<div class='left'>"
				ul_html += "<div class='title'>" + obj.title + "</div>"
				ul_html += "<div class='info'>"
				ul_html += "<span>" + obj.source + "</span>"
				ul_html += "<span>" + obj.time + "</span>"
				ul_html += "</div>"
				ul_html += "</div>"
				ul_html += "<div class='right'>"
				ul_html += "<img src='" + obj.img + "' alt=''>"
				ul_html += "</div>"
				ul_html += "</li>"
			}
			$('ul:first').html(ul_html) // 覆盖原来的html文本
		}
	</script>
</html>